﻿using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.IO;
using Labthink.PCSoft.UniversalHost4.Model;
using Labthink.PCSoft.UniversalHost4.Utility;
using NLog;

namespace SystemSettings
{
    public class ReportConfigManager
    {
        private static readonly Logger logger = LogManager.GetCurrentClassLogger();

        public static List<ReportConfig> GetConfigs()
        {
            ExistDb();
            logger.Debug("获取全部报告配置");
            var cfgs = new List<ReportConfig>();
            try
            {
                var con = new SQLiteConnection(SqliteHelper.CreateConnectionString(ConfigAndSettings.UnitDb));
                con.Open();
                using var cmd = con.CreateCommand();
                var reader = SqliteHelper.ExecuteReader(cmd, "SELECT * FROM ReportConfig  ", null);
                while (reader.Read())
                {
                    cfgs.Add(new ReportConfig
                    {
                        Type = reader["Type"].ToInt32(),
                        Param = reader["Param"].ToString(),
                        Result = reader["Result"].ToString(),
                        DataCurve = reader["DataCurve"].ToString(),
                        DataList = reader["DataList"].ToString(),
                        ResultCurve = reader["ResultCurve"].ToString()
                    });
                }
                reader.Close();
            }
            catch (Exception e)
            {
                logger.Error("查询所有报告配置出错:{0}", e, "SELECT * FROM ReportConfig");
            }

            return cfgs;
        }

        public static int UpdateConfig(ReportConfig config)
        {
            ExistDb();
            logger.Debug("更新报告配置");
            var c = SqliteHelper.ExecuteScalar(ConfigAndSettings.UnitDb,
                "SELECT COUNT(1) FROM ReportConfig WHERE Type=@type", config.Type).ToInt32();
            string sql;
            if (c == 0)
            {
                sql =
                    "INSERT INTO ReportConfig (Type, Param, Result,DataCurve,DataList, ResultCurve) VALUES (@Type,@Param,@Result,@DataCurve,@DataList, @ResultCurve)";
                return SqliteHelper.ExecuteNonQuery(ConfigAndSettings.UnitDb, sql, config.Type, config.Param,
                    config.Result, config.DataCurve, config.DataList, config.ResultCurve);
            }
            sql =
                "UPDATE ReportConfig SET Param=@Param, Result=@Result,DataCurve=@DataCurve,DataList=@DataList,ResultCurve=@ResultCurve WHERE Type=@Type";
            return SqliteHelper.ExecuteNonQuery(ConfigAndSettings.UnitDb, sql, config.Param,
                  config.Result, config.DataCurve, config.DataList, config.ResultCurve, config.Type);
        }

        private static void ExistDb()
        {
            if (!File.Exists(ConfigAndSettings.UnitDb))
            {
                throw new FileNotFoundException("Db file is not exists");
            }
        }
    }
}
